<?php


namespace app\common\utils;


class CurlUtil extends BaseUtil
{
    static $_self = null;
    public static function getInstance(){
        if(empty(self::$_self)){
            self::$_self = new CurlUtil();
        }
        return self::$_self;
    }

    /**
     * @param string $openid
     * @param string $template_id
     * @param array  $mess_data
     * @param string $jump_url
     * @param string $type 公众号、小程序消息通知
     * @param string $form_id 仅小程序消息通知有效
     * @return mixed
     */
    function templateMess($openid, $template_id, $mess_data, $jump_url='', $type='public', $form_id=''){//发送模板消息 公众号
        $access_token = $this->getToken($type);
        $data['touser'] = $openid;
        $data['template_id'] = $template_id;
        $data['data'] = $mess_data;
        if( $type=='small' ){
            $data['form_id'] = $form_id;
            $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$access_token}";
            $data['page'] = $jump_url;
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
            $data['url'] = $jump_url;
        }
        return $this->httpCurl($url, $data);
    }
    /**
     * 获取太阳码
     * @param $scene str 太阳码参数
     */
    public function getQrcode($scene){
        $data = ['scene'=>$scene];
        $access_token = $this->getToken('small');
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        $res = $this->httpCurl($url, $data);
        $base_img = str_replace('data:image/jpg;base64,', '', $res);
        return $base_img;
    }
    /*
   * 获取用户信息
   * $type （snsapi_base关注公众号静默授权，snsapi_userinfo感知授权）
   * $redirect_uri 回调地址
   */
    function getUserInfo($type, $redirect_uri){
        $appid = config('project.PUBLIC_WECHAT.APPID');
        if( !isset($_GET['code']) ){
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$type}&state=STATE#wechat_redirect";
            header('Location:' . $url);die;
        }else{
            $appsecret = config('project.PUBLIC_WECHAT.APPSECRET');
            $as_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$_GET['code']}&grant_type=authorization_code ";
            $assres = json_decode( $this->httpCurl($as_url),true );
            if($type=='snsapi_base'){
                $token = $this->getToken('public');
                $url ="https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$assres['openid']}&lang=zh_CN";
            }else if($type=='snsapi_userinfo'){
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$assres['access_token']}&openid={$assres['openid']}&lang=zh_CN";
            }
            return json_decode( $this->httpCurl($url),true );
        }
    }
    /*
     * 获取token
     * @param $type string public(公众号) small(小程序)
     * @return $token string
     */
    public function getToken($type)
    {
        $cache_name = "{$type}_token";
        if (cache($cache_name)) {
            return cache($cache_name);
        } else {
            if ($type == 'small') {
                $appid = config('project.APPLET_WECHAT.APPID');
                $appsecret = config('project.APPLET_WECHAT.APPSECRET');
            } elseif ($type == 'public') {
                $appid = config('project.PUBLIC_WECHAT.APPID');
                $appsecret = config('project.PUBLIC_WECHAT.APPSECRET');
            }
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $res = json_decode($this->httpCurl($url), true);
            if (isset($res['access_token'])) {
                cache($cache_name, $res['access_token'], 7150);
                return $res['access_token'];
            }
        }
    }
    /** curl请求
     * @param       $url
     * @param       $postData
     * @return bool|string
     */
    public function httpCurl($url, $postData=[]){
        if(is_array($postData)){
            $postData = json_encode($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type:application/json'));
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}